﻿
    using System;
    using System.Collections.Generic;
    using System.Windows;
    using System.Windows.Controls;
namespace WCYCReader.Drawing
{
    public class BufferedImageExtendedImpl : BufferedImageImpl, BufferedImageExtended
    {
        private List<Canvas> canvases;

        public BufferedImageExtendedImpl(sbyte[] data) : base(data)
        {
        }

        public BufferedImageExtendedImpl(int width, int height, int type) : base(width, height, type)
        {
        }

        private void clearCanvases()
        {
            if (this.canvases != null)
            {
                foreach (Canvas canvas in this.canvases)
                {
                    this.DeepClear(canvas);
                }
                this.canvases.Clear();
            }
        }

        public AffineTransform createAffineTransform()
        {
            return new AffineTransformImpl();
        }

        public GraphicsExtended createGraphics()
        {
            if (base.graphics == null)
            {
                base.graphics = new GraphicsRecorder(base.width, base.height);
            }
            return (GraphicsExtended) base.graphics;
        }

        private void DeepClear(Canvas canvas)
        {
            foreach (UIElement element in canvas.Children)
            {
                if (element is Canvas)
                {
                    this.DeepClear((Canvas) element);
                }
            }
            canvas.Children.Clear();
        }

        public void dispose()
        {
            this.clearCanvases();
        }

        public WritableRaster getRaster()
        {
            return new WritableRasterImpl(base.graphics);
        }

        public override UIElement getUIElement(Rect clip)
        {
            if ((base.graphics == null) || !(base.graphics is GraphicsRecorder))
            {
                return base.getUIElement(clip);
            }
            UIElement element = ((GraphicsRecorder) base.graphics).Playback(null, clip);
            if (this.canvases == null)
            {
                this.canvases = new List<Canvas>();
            }
            this.canvases.Add((Canvas) element);
            return element;
        }

        public void onRecycled()
        {
            this.clearCanvases();
        }
    }
}

